package A一周刷爆LeetCode.A基础班.E链表;

/**
 * @author wei.zhao
 * @description: 反转链表
 * @date 2022年01月24日 11:22
 */
public class Code02_ReverseList {

    public static void main(String[] args) {
        //单向链表
        Node head1 = new Node(1);
        head1.next = new Node(2);
        head1.next.next = new Node(3);
        head1.next.next.next = new Node(4);
        head1.next.next.next.next = new Node(5);
        head1.next.next.next.next.next = new Node(6);
        head1.next.next.next.next.next.next = new Node(7);
        printLinkedList(head1);
        head1 = reverseList(head1);
        printLinkedList(head1);
        //双向链表
        DoubleNode head2 = new DoubleNode(1);
        head2.next = new DoubleNode(2);
        head2.next.last = head2;
        head2.next.next = new DoubleNode(3);
        head2.next.next.last = head2.next;
        head2.next.next.next = new DoubleNode(4);
        head2.next.next.next.last = head2.next.next;
        printDoubleLinkedList(head2);
        printDoubleLinkedList(reverseList(head2));
    }

    //反转单向链表
    public static Node reverseList(Node head) {
        Node preNode = null;
        while (head != null) {
            Node next = head.next;
            head.next = preNode;
            preNode = head;
            head = next;
        }
        return preNode;
    }

    //反转双向链表
    public static DoubleNode reverseList(DoubleNode head) {
        DoubleNode preNode = null;
        while (head != null) {
            DoubleNode next = head.next;
            head.next = preNode;
            head.last = next;
            preNode = head;
            head = next;
        }
        return preNode;
    }

    public static void printLinkedList(Node head) {
        System.out.print("Linked List: ");
        while (head != null) {
            System.out.print(head.value + " ");
            head = head.next;
        }
        System.out.println();
    }

    public static void printDoubleLinkedList(DoubleNode head) {
        System.out.print("Double Linked List: ");
        DoubleNode end = null;
        while (head != null) {
            System.out.print(head.value + " ");
            end = head;
            head = head.next;
        }
        System.out.print("| ");
        while (end != null) {
            System.out.print(end.value + " ");
            end = end.last;
        }
        System.out.println();
    }

}
